import re

from django.contrib.auth.models import User
from django.db import models

# Create your models here.

from django.utils import timezone
from markdown import Markdown


class Avatar(models.Model):
    """文章标题图片"""
    content = models.ImageField(upload_to='avatar/%y%m%d')


class Tag(models.Model):
    """标签"""
    text = models.CharField(verbose_name="标签", max_length=30)

    def __str__(self):
        return self.text

    class Meta:
        ordering = ['-id']


class Category(models.Model):
    """文章分类"""
    title = models.CharField(verbose_name='分类', max_length=100)
    create_datetime = models.DateTimeField(verbose_name="创建时间", default=timezone.now)

    def __str__(self):
        return self.title

    class Meta:
        ordering = ['-create_datetime']


class Article(models.Model):
    title = models.CharField(verbose_name="标题", max_length=100)
    body = models.TextField(verbose_name="正文")
    create_datetime = models.DateTimeField(verbose_name="创建时间", default=timezone.now)
    updated_datetime = models.DateTimeField(verbose_name="更新时间", auto_now=True)

    # 添加作者外键(映射后，实际字段名称为author_id)
    author = models.ForeignKey(
        User,
        null=True,
        on_delete=models.CASCADE,  # 级联删除，也就是作者对象被删除，对应的文章也被删除
        related_name='articles'
    )

    # 添加分类外键
    category = models.ForeignKey(
        Category,
        null=True,
        blank=True,
        on_delete=models.SET_NULL,  # 分类被删除后，置空（前提是该字段允许为空）
        related_name='articles'
    )

    # 添加标签外键
    tags = models.ManyToManyField(
        Tag,
        blank=True,
        related_name='articles'
    )

    # 文章标题图
    avatar = models.ForeignKey(
        Avatar,
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='article'  #
    )

    # 新增方法，将 body 转换为带 html 标签的正文
    def get_md(self):
        md = Markdown(
            extensions=[
                'markdown.extensions.extra',
                'markdown.extensions.codehilite',
                'markdown.extensions.toc',
            ]
        )
        md_body = md.convert(self.body)  # body字段转换为markdown数据
        m = re.search(r'<div class="toc">\s*<ul>(.*)</ul>\s*</div>', md.toc, re.S)
        # toc 是渲染后的目录
        return md_body, m.group(1) if m is not None else ''

    def __str__(self):
        return self.title

    class Meta:
        ordering = ['-create_datetime']  # 排序：时间倒序
